<html>
<head><title>CS143 Project 1B Demo</title></head>
<body>
Type an SQL query in the following box:
<p>
<form action="" method="POST">
<textarea name="query" cols="60" rows="8">SHOW TABLES;</textarea>
<input type="submit" value="Submit" />
</form>
</p>

<?php
$db_connection = mysql_connect("localhost", "cs143", "");

mysql_select_db("cs143", $db_connection);

$query = $_POST['query'];
$sanitized_query = mysql_real_escape_string($query, $db_connection);
$query_to_issue = sprintf($query, $sanitized_query);
$rs = mysql_query($query_to_issue, $db_connection);

if ($error = mysql_error()) {
	print "Could not run query: $error";
	exit;
}
else {
	print "<h3>Results from MySQL:</h3>";
	print "<table border='1'>";
	print "<tr>";
	$i = 0;
        while($i < mysql_num_fields($rs)){
                echo "<td>" . "<b>" . mysql_field_name($rs, $i) . "</b>" . "</td>";
                $i++; 
        }
	print "</tr>";
	while($row = mysql_fetch_row($rs)) {
		print"<tr>";
		for($i = 0; $i < count($row); $i++){
			print "<td>$row[$i]</td>";
		}	
		print "</tr>";
	}
	print"</table>";
}
mysql_close($db_connection);
?>

</body>
</html>
